/**
 * Created by bestick on 2015/12/27.
 * 全局函数库
 */
//Json渲染
function $render(tempId, domId, data, callback) {
    var template = $.templates(tempId);
    var htmlOutput = template.render(data);
    $(domId).html(htmlOutput);
    if ($.isFunction(callback)) {
        callback();
    }
}

//Ajax请求返回Json成功则调用$render
function doRender(url, args, map, callback) {
    var $ajax = $.ajax({
        type: "GET",
        url: url,
        data: args,
        dataType: "json",
        timeout: 15000,
        success: function (data) {
            for (var prop in map) {
                // console.log(prop + ":" + map[prop]);
                $render(prop, map[prop], data);
            }
        },
        complete: function (XMLHttpRequest, status) {
            if ($.isFunction(callback)) {
                callback(XMLHttpRequest);
            }
            if (status == "error") {
                showErrorInfo("error code: " + XMLHttpRequest.status);
            } else if (status == "timeout") {
                $ajax.abort();
                showErrorInfo('请求超时');
            }
        }
    });
}

//向服务器提交数据
function doPost(url, args, callback) {
    var $ajax = $.ajax({
        type: "POST",
        url: url,
        data: args,
        timeout: 15000,
        success: function () {
            alert("提交成功！")
        },
        complete: function (XMLHttpRequest, status) {
            if (status == "error") {
                alert("error code: " + XMLHttpRequest.status);
            } else if (status == "timeout") {
                $ajax.abort();
                alert('请求超时');
            }
            if ($.isFunction(callback)) {
                callback(XMLHttpRequest);
            }
        }
    });
}

//获取当前时间戳
function now() {
    return new Date().getTime();
}

//layer错误信息弹出层
function showErrorInfo(msg) {
    layer.msg(msg, {
        shade: 0.3,
        shadeClose: true,
        icon: 5,
        time: 2000, //2秒关闭
    });
}

//layer成功信息弹出层
function showInfo(msg, callback) {
    layer.msg(msg, {
        time: 1500, //1.5秒关闭
    }, function () {
        callback.apply();
    });
}

//layer确认信息弹出层
// function showConfirm(msg, callback) {
//    
// }

//创建一个StringBuffer方法
function StringBuffer() {
    this.__strings__ = [];
};
StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
    return this.__strings__.join('');
};

//jsRender自定义标签
var renderHelper = $.views.tags({
    sysConstants: function (context, option) {
        if (sysConstants) {
            return sysConstants['contants'][option][context];
        } else {
            return context;
        }
    },
    wan: function (context) {
        if (context == undefined || context == "") return 0;
        var money = context.toString() * 1;
        return Math.round(money / 10000 * 100) / 100;
    },
    moneyFormat: function (context) {
        if (context == undefined || context == "") return 0;
        var money = context.toString() * 1;
        if (money >= 10000000) {
            return Math.round(money / 100000000 * 100) / 100 + "亿";
        }
        if (money >= 10000) {
            return Math.round(money / 10000 * 100) / 100 + "万";
        }
        return money + "元";
    },
    portionFormat: function (context) {
        if (context == undefined || context == "") return 0;
        var portion = context.toString() * 1;
        if (portion >= 10000000) {
            return Math.round(portion / 100000000 * 100) / 100 + "亿份";
        }
        if (portion >= 10000) {
            return Math.round(portion / 10000 * 100) / 100 + "万份";
        }
        return portion + "分";
    },
    dateFormat: function (context, type) {
        if (type == "normal") {  //e.g. dateTime(原样返回): yyyy-mm-dd HH:mm:ss
            return context.toString();
        }
        if (type == "numDate2NormalDate") {  //e.g. numDate(20151114这样的数字格式化成yyyy-mm-dd)
            var date = context.toString();
            var year = date.substring(0, 4);
            var month = date.substring(4, date.length - 2);
            month = (month.length == 2) ? month : ('0' + month);
            var day = date.substring(date.length - 2);
            return year + '-' + month + '-' + day;
        }
        if (type == "normalDate") {  //e.g. normalDate(去掉time,返回date): yyyy-mm-dd
            var year = context.substring(2, 4);
            var month = context.substring(5, 7);
            var date = context.substring(8, 10);
            return year + "-" + month + "-" + date;
        }
        if (type == "timeStamp2DateTime") {
            var date = new Date(parseInt(context));
            var year = date.getFullYear();
            var month = fillZero(date.getMonth() + 1);
            var day = fillZero(date.getDate());
            var hour = fillZero(date.getHours());
            var minute = fillZero(date.getMinutes());
            var second = fillZero(date.getSeconds());
            return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        }
        if (type == "timeStamp2HoursTime") {
            var date = new Date(parseInt(context));
            var hour = fillZero(date.getHours());
            var minute = fillZero(date.getMinutes());
            return hour + ':' + minute;
        }
        return context;
    },
    doubleFormat: function (context, option) {
        if (context == undefined || context == "") return 0.0;
        if (option == "normal") return context;
        return (context * 1).toFixed(1);
    },
    feeBuyRange: function (index, floor, top, standardBuyRate) {
        var floorFormat = (floor == 0 || floor == null) ? '' : (moneyFormat(floor) + '≤');
        var topFormat = (top == 0 || top == null) ? "" : ('<' + moneyFormat(top));
        standardBuyRate = doubleFormat(standardBuyRate, "normal");
        var td1 = '<td rowspan="4" class="head">前端申购</td>';
        var td2 = '<td class="text-left">' + floorFormat + '申购金额' + topFormat + '<span class="pull-right">' + standardBuyRate + '%</span></td>';
        return index == 0 ? '<tr>' + td1 + td2 + '</tr>' : '<tr>' + td2 + '</tr>';
    }
});

function moneyFormat(context) {
    if (context == undefined || context == "") return 0;
    var money = context.toString() * 1;
    if (money >= 10000000) {
        return Math.round(money / 100000000 * 100) / 100 + "亿";
    }
    if (money >= 10000) {
        return Math.round(money / 10000 * 100) / 100 + "万";
    }
    return money + "元";
}

function doubleFormat(context, option) {
    if (context == undefined || context == "") return 0.00;
    if (option == "normal") return context;
    return (context * 1).toFixed(2);
}

function fillZero(context) {
    if (context > 9) return context;
    return '0' + context;
}

//动态获取分页组件
function genPagination(total, count, nowPage) {
    //总页数
    var totalPage = total % count == 0 ? total / count : parseInt(total / count) + 1;
    var buffer = new StringBuffer();
    buffer.append('<div class="page-nav jcb-page-nav"><ul class="pagination jcb-pagination">');
    //首页
    buffer.append("<li><a class='jcb-page-first' data-page='1'>首页</a></li>");
    //上一页逻辑
    if (nowPage == 1) {
        buffer.append("<li class='disabled'><a class='jcb-page-pre' data-page='" + nowPage + "'>上一页</a></li>");
    } else {
        buffer.append("<li><a class='jcb-page-pre' data-page='" + eval(nowPage - 1) + "'>上一页</a></li>");
    }
    //中间页逻辑
    for (var i = nowPage - 2; i <= nowPage + 2; i++) {
        if (i < 1 || i > totalPage) {
            continue;
        }
        if (i == nowPage) {
            buffer.append("<li class='active'><a class='jcb-page-this' data-page='" + i + "'>" + i + "</a></li>");
        } else {
            buffer.append("<li><a class='jcb-page-this' data-page='" + i + "'>" + i + "</a></li>");
        }
    }
    //下一页逻辑
    if (nowPage == totalPage) {
        buffer.append("<li class='disabled'><a class='jcb-page-next' data-page='" + totalPage + "'>下一页</a></li>");
    } else {
        buffer.append("<li><a class='jcb-page-next' data-page='" + eval(nowPage + 1) + "'>下一页</a></li>");
    }
    //末页
    buffer.append("<li><a class='jcb-page-last' data-page='" + totalPage + "'>末页</a></li>");

    buffer.append('</ul></div>');
    return buffer.toString();
}

//评论渲染
function commentRender($obj, url, pid, nowPage, count, map, callback) {
    doRender(
        url,
        {
            "commentBelongToProduct": pid,
            "start": (nowPage - 1) * count,
            "count": count,
            "t": now()
        },
        map,
        function (XMLHttpRequest) {
            //获取total
            var total = eval('(' + XMLHttpRequest.responseText + ')').total;
            if (total > 0) {
                //在目标节点后append分页组件
                $obj.append(genPagination(total, count, nowPage));
                initPagination($obj, url, pid, nowPage, count, map, callback);
            }
        }
    )
}

//分页实现
function initPagination($obj, url, pid, nowPage, count, map, callback) {

    $('.jcb-page-first').click(function () {
        if (nowPage == 1) return;
        nowPage = 1;
        callback($obj, url, pid, nowPage, count, map, callback);
    });

    $('.jcb-page-last').click(function () {
        if (nowPage == $(this).data('page')) return;
        nowPage = $(this).data('page');
        callback($obj, url, pid, nowPage, count, map, callback);
    });

    $('.jcb-page-next').click(function () {
        if (nowPage >= $(this).data('page')) return;
        nowPage++;
        callback($obj, url, pid, nowPage, count, map, callback);
    });

    $('.jcb-page-pre').click(function () {
        if (nowPage <= $(this).data('page')) return;
        nowPage--;
        callback($obj, url, pid, nowPage, count, map, callback);
    });

    $('.jcb-page-this').click(function () {
        if (nowPage == $(this).data('page')) return;
        nowPage = $(this).data('page');
        callback($obj, url, pid, nowPage, count, map, callback);
    });
}

//初始化理财计算器
function initJCBCalculator() {
    $('#jcb-calculator-slider').slider({
        tooltip: 'always'
    });
    //ctrl
    $('.jcb-cal-slider .slider-track').on("click", function () {
        $('#jcb-cal-amount').val($('#jcb-calculator-slider').val());
        $('#jcb-cal-sum').text(($('#jcb-cal-amount').val() * $('#jcb-cal-yield').text() / 100 * $('#jcb-cal-term').val()).toFixed(2));
        initJcbCalChart();
    });
    $('#jcb-calculator-slider').bind("slide", function (evt) {
        $('#jcb-cal-amount').val(evt.value);
        $('#jcb-cal-sum').text((evt.value * $('#jcb-cal-yield').text() / 100 * $('#jcb-cal-term').val()).toFixed(2));
        initJcbCalChart();
    });
    //TODO reverse-ctrl
    $('#jcb-cal-amount').bind("input propertychange", function () {
        //重新加载slider
        $('#jcb-calculator-slider').attr('data-slider-value', $(this).val());
        $('#jcb-calculator-slider').slider();
    });
}

//初始化理财计算器图表
function initJcbCalChart() {
    $(function () {
        $('#jcb-cal-chart').highcharts({
            chart: {
                type: 'column',
                animation: false
            },
            title: {
                text: '收益本金图表'
            },
            xAxis: {
                categories: ['24month']
            },
            yAxis: {
                title: {
                    text: '万元'
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: '本金',
                data: [Number($('#jcb-calculator-slider').val())],
                color: '#fed65a'
            }, {
                name: '收益',
                data: [Number(($('#jcb-cal-amount').val() * $('#jcb-cal-yield').text() / 100 * $('#jcb-cal-term').val()).toFixed(2))],
                color: '#d3d9df'
            }]
        });
    });
}